package org.springblade.modules.repair.service.impl;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.config.ProjectApiConfiguration;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.repair.service.IPartsShopService;
import org.springblade.modules.repair.vo.part.shop.SkuDetailVO;
import org.springblade.modules.system.vo.PartsShopUnitVO;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author ysq
 * @Date 2024/12/23
 * @Description 配件商城接口实现类
 */
@Slf4j
@AllArgsConstructor
@Service
public class PartsShopServiceImpl implements IPartsShopService {

	private final ProjectApiConfiguration projectApiConfiguration;
	@Override
	public SkuDetailVO skuDetail(Long skuId) throws Exception{
		String url = projectApiConfiguration.getParts() + "/parts/skuinfo/detail?enable=1&id=" + skuId;
		try {
			String res = HttpUtil.get(url, 10000);
			JSONObject jsonObject = JSONObject.parseObject(res);
			SkuDetailVO detail = jsonObject.getJSONObject("data").toJavaObject(SkuDetailVO.class);
			return detail;
		} catch (HttpException e) {
			log.error("请求配件商城接口失败，url: " + url);
			throw new ServiceException("请求配件商城接口失败");
		}
	}

	@Override
	public List<PartsShopUnitVO> getPartsShopUnit()  throws Exception{
		String url = projectApiConfiguration.getParts() + "/parts/unit/list";
		try {
			String res = HttpUtil.get(url, 10000);
			JSONObject jsonObject = JSONObject.parseObject(res);
			if(Func.isNotEmpty(jsonObject)  && jsonObject.containsKey("data")){
				JSONArray jsonArray = jsonObject.getJSONArray("data");
				// 转换成VO
                return jsonArray.toJavaList(PartsShopUnitVO.class);
			}
		} catch (HttpException e) {
			log.error("请求配件商城接口失败，url: " + url);
			throw new ServiceException("请求配件商城接口失败");
		}
        return new ArrayList<>();
    }

	@Override
	public String getCategoryPathName(Long categoryId) {
		String url = projectApiConfiguration.getParts() + "/parts/category/get/path/name?categoryId=" + categoryId;
		try {
			String res = HttpUtil.get(url, 10000);
			JSONObject jsonObject = JSONObject.parseObject(res);
			String path = jsonObject.getJSONObject("data").toString();
			return path;
		} catch (HttpException e) {
			log.error("请求配件商城接口失败，url: " + url);
			throw new ServiceException("请求配件商城接口失败");
		}
	}
}
